package com.cmcc.sdtp.sdtp.util;

import java.security.DigestException;
import java.security.SignatureException;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.cmcc.sdtp.sdtp.message.LinkAuthReqMsg;
import com.cmcc.sdtp.util.SdtpPropertiesUtil;
import com.google.common.base.Charsets;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;

public class AuthUtil {

	private static Logger logger = LogManager.getLogger(AuthUtil.class);

	
	private static Map<String, String> secretMap;

	static {
		secretMap = new HashMap<String, String>();
		secretMap.put(SdtpPropertiesUtil.getProperty("LoginID"), SdtpPropertiesUtil.getProperty("Sharedsecret"));
	}

	public static String linkAuth(LinkAuthReqMsg reqBody) throws SignatureException, DigestException {
		String ifLingkAuth = SdtpPropertiesUtil.getProperty("IF_LINGK_AUTH");//是否开启鉴权
		logger.info("是否开启鉴权请求：" + ifLingkAuth);
		if("true".equals(ifLingkAuth)){
//			String secretHash = AuthUtil.MD5(AuthUtil.getAuthSecret(reqBody.getLoginID()));
//			if (DPIPropertiesUtil.getProperty("Digest").equals("SHA256"))
			String secretHash = AuthUtil.SHA256(AuthUtil.getAuthSecret(reqBody.getLoginID()));
			String loginId = SdtpPropertiesUtil.getProperty("LoginID") + "            ";
			String str =  loginId.substring(0, 12) + secretHash + reqBody.getTimestamp() + "rand=" + reqBody.getRand();
			// 按照规则补零
			String digest = AuthUtil.SHA256(str) + "0000000000000000000000000000000000000000000000000000000000000000";
			logger.info("digest（service端）：" + digest);
			logger.info("digest（client端）：" + reqBody.getDigest());
			// 验证失败
			if (!digest.equals(reqBody.getDigest())) {
				logger.error("SHA256验证未通过" + reqBody.getDigest());
				throw new DigestException("SHA256验证未通过");
			}
			return digest;
		}
		return reqBody.getDigest();
	}

	/**
	 * 根据loginID查询对应的Shared secret
	 * 
	 * @param loginID
	 * @return
	 * @throws SignatureException
	 *             LoginID不存在。
	 */
	public static String getAuthSecret(String loginID) throws SignatureException {
		String secret = secretMap.get(loginID.trim());
		if (Util.checkNull(secret)) {
			throw new SignatureException("LoginID不存在");
		}
		return secret;
	}

	/**
	 * @comment sha256加密字符串 google大法好！
	 * 
	 * @param text
	 * @return
	 */
	public static String SHA256(String text) {
		String result = Hashing.sha256().hashString(text, Charsets.UTF_8).toString();
		return result;
	}

	/**
	 * @comment MD5加密字符串
	 * 
	 * @param text
	 * @return
	 */
	public static String MD5(String text) {
		String result = Hashing.md5().hashString(text, Charsets.UTF_8).toString();
		return result;
	}

	/**
	 * 将字节数组转换为hex字符串
	 * 
	 * @param data
	 * @return
	 */
	public static String toHex(byte[] data) {
		return HashCode.fromBytes(data).toString();
	}

}